import 'package:blurb/common/values/svg.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import '../../common/store/topic_store.dart';
import '../../common/store/user_store.dart';
import '../../common/models/user.dart';
import '../../common/models/topic.dart';
import 'package:go_router/go_router.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class TopicPublishPage extends StatefulWidget {
  const TopicPublishPage({super.key});

  @override
  State<TopicPublishPage> createState() => _TopicPublishPageState();
}

class _TopicPublishPageState extends State<TopicPublishPage> {
  final TextEditingController _titleController = TextEditingController();
  final TextEditingController _descController = TextEditingController();
  bool _isLoading = false;
  User? _currentUser;
  static const String _draftKey = 'topic_draft';

  @override
  void initState() {
    super.initState();
    final userStore = Provider.of<UserStore>(context, listen: false);
    _currentUser = userStore.currentUser;
    _loadDraft();
  }

  Future<void> _loadDraft() async {
    if (_currentUser == null) return;
    final prefs = await SharedPreferences.getInstance();
    final draftStr = prefs.getString(_draftKey + '_${_currentUser!.id}');
    if (draftStr != null) {
      final draftMap = jsonDecode(draftStr);
      setState(() {
        _titleController.text = draftMap['title'] ?? '';
        _descController.text = draftMap['desc'] ?? '';
      });
    }
  }

  Future<void> _saveDraft() async {
    if (_currentUser == null) return;
    final prefs = await SharedPreferences.getInstance();
    final draftMap = {
      'title': _titleController.text,
      'desc': _descController.text,
      'timestamp': DateTime.now().toIso8601String(),
    };
    await prefs.setString(_draftKey + '_${_currentUser!.id}', jsonEncode(draftMap));
  }

  Future<void> _clearDraft() async {
    if (_currentUser == null) return;
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_draftKey + '_${_currentUser!.id}');
  }

  Future<void> _publishTopic() async {
    if (_titleController.text.trim().isEmpty || _descController.text.trim().isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Title and description cannot be empty')),
      );
      return;
    }
    setState(() => _isLoading = true);
    try {
      final topicStore = Provider.of<TopicStore>(context, listen: false);
      final allTopics = topicStore.topics;
      final newTopicId = allTopics.isEmpty ? 1 : allTopics.map((t) => t.id).reduce((a, b) => a > b ? a : b) + 1;
      final topic = Topic(
        id: newTopicId,
        title: _titleController.text.trim(),
        description: _descController.text.trim(),
        userId: _currentUser?.id ?? 0,
      );
      await topicStore.addTopic(topic);
      await _clearDraft();
      if (mounted) {
        GoRouter.of(context).pop();
      }
    } finally {
      if (mounted) setState(() => _isLoading = false);
    }
  }

  void _showSaveDraftDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        backgroundColor: const Color(0xFF1F1F21),
        title: Text(
          'Save Draft',
          style: GoogleFonts.racingSansOne(
            color: Colors.white,
            fontSize: 24.sp,
          ),
        ),
        content: Text(
          'After saving the draft, the currently entered content will not be lost after exiting the page.',
          style: GoogleFonts.racingSansOne(
            color: Colors.white,
            fontSize: 16.sp,
            fontWeight: FontWeight.normal,
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: Text(
              'Cancel',
              style: GoogleFonts.racingSansOne(
                color: Colors.white70,
                fontSize: 18.sp,
                fontWeight: FontWeight.normal,
              ),
            ),
          ),
          GestureDetector(
            onTap: () async {
              await _saveDraft();
              if (mounted) {
                Navigator.of(context).pop();
                GoRouter.of(context).pop();
              }
            },
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 10.h),
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  begin: Alignment(0.50, 0.00),
                  end: Alignment(0.50, 0.96),
                  colors: [Color(0xFF60C3FF), Color(0xFFAADEFC)],
                ),
                borderRadius: BorderRadius.circular(30.r),
              ),
              child: Text(
                'Save',
                style: GoogleFonts.racingSansOne(
                  color: Colors.white,
                  fontSize: 18.sp,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final avatar = _currentUser?.avatar ?? 'assets/images/avatar.png';
    final nickname = _currentUser?.nickname ?? 'Guest';

    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios, color: Colors.white),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text(
          'Release',
          style: GoogleFonts.racingSansOne(
            color: Colors.white,
            fontWeight: FontWeight.normal,
            fontSize: 24.sp,
          ),
        ),
        centerTitle: true,
        actions: [
          TextButton(
            onPressed: _showSaveDraftDialog,
            child: Text(
              'Save Draft',
              style: GoogleFonts.racingSansOne(
                color: Colors.white,
                fontWeight: FontWeight.normal,
                fontSize: 16.sp,
                decoration: TextDecoration.underline,
                decorationColor: Colors.white,
                decorationThickness: 1.w,
                decorationStyle: TextDecorationStyle.solid,
              ),
            ),
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator(color: Color(0xFF60C3FF)))
          : Column(
              children: [
                SizedBox(height: 20.h),
                // 用户头像和提示文本
                Center(
                  child: Column(
                    children: [
                      Container(
                        width: 80.w,
                        height: 80.h,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          border: Border.all(color: Colors.white, width: 2.w),
                          image: DecorationImage(
                            image: AssetImage(avatar),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                      SizedBox(height: 10.h),
                      Text(
                        nickname,
                        style: GoogleFonts.racingSansOne(
                          color: Colors.white,
                          fontSize: 18.sp,
                          fontWeight: FontWeight.normal,
                        ),
                      ),
                      SizedBox(height: 5.h),
                      Text(
                        'Share your sun protection tips now',
                        style: GoogleFonts.inter(
                          color: Colors.white70,
                          fontSize: 14.sp,
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(height: 20.h),
                // 标题输入框
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Container(
                    padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                    decoration: BoxDecoration(
                      color: const Color(0xFF1F1F21),
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: TextField(
                      controller: _titleController,
                      style: GoogleFonts.inter(
                        color: Colors.white,
                      ),
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: 'Enter A Title',
                        hintStyle: GoogleFonts.inter(
                          color: Colors.grey,
                        ),
                        icon: Icon(MSI.edit, color: Colors.grey),
                      ),
                    ),
                  ),
                ),
                SizedBox(height: 16.h),
                // 主题描述输入框
                Padding(
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Container(
                    height: 240.h,
                    padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                    decoration: BoxDecoration(
                      color: const Color(0xFF1F1F21),
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: TextField(
                      controller: _descController,
                      style: GoogleFonts.inter(
                        color: Colors.white,
                      ),
                      maxLines: null,
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: 'Enter The Topic Description',
                        hintStyle: GoogleFonts.inter(
                          color: Colors.grey,
                        ),
                        icon: Icon(MSI.edit, color: Colors.grey),
                      ),
                    ),
                  ),
                ),
                const Spacer(),
                // 底部按钮
                Padding(
                  padding: EdgeInsets.all(16.w),
                  child: Column(
                    children: [
                      GestureDetector(
                        onTap: _publishTopic,
                        child: Container(
                          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                          width: double.infinity,
                          height: 56.h,
                          decoration: BoxDecoration(
                            gradient: const LinearGradient(
                              begin: Alignment(0.50, 0.00),
                              end: Alignment(0.50, 0.96),
                              colors: [
                                Color(0xFF60C3FF),
                                Color(0xFFAADEFC),
                              ],
                            ),
                            borderRadius: BorderRadius.circular(39.r),
                          ),
                          child: Center(
                            child: Text(
                              'Release',
                              style: GoogleFonts.racingSansOne(
                                color: Colors.white,
                                fontSize: 18.sp,
                                fontWeight: FontWeight.normal,
                              ),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 4.h),
                      TextButton(
                        onPressed: () {
                          _titleController.clear();
                          _descController.clear();
                        },
                        child: Center(
                          child: Text(
                            'Reset',
                            style: GoogleFonts.racingSansOne(
                              color: Colors.white,
                              fontSize: 16.sp,
                              fontWeight: FontWeight.normal,
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: 16.h),
                      Text(
                        'EULA',
                        style: GoogleFonts.inter(
                          color: Colors.white.withOpacity(0.8),
                          fontSize: 12.sp,
                          fontWeight: FontWeight.w500,
                          decoration: TextDecoration.underline,
                          decorationColor: Colors.white.withOpacity(0.8),
                          decorationThickness: 1.w,
                          decorationStyle: TextDecorationStyle.solid,
                        ),
                      ),
                      SizedBox(height: 20.h),
                    ],
                  ),
                ),
              ],
            ),
    );
  }
}